package com.farmer.auth.controller;

import com.farmer.auth.service.AuthService;
import com.farmer.common.dto.LoginDTO;
import com.farmer.common.dto.RegisterDTO;
import com.farmer.common.result.Result;
import com.farmer.common.utils.PasswordEncoder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@Tag(name = "认证管理", description = "用户登录、注册、认证相关接口")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户使用用户名和密码进行登录")
    public Result<?> login(@Valid @RequestBody LoginDTO loginDTO) {
        log.info("用户登录请求：{}", loginDTO.getUsername());
        return authService.login(loginDTO);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册账号")
    public Result<?> register(@Valid @RequestBody RegisterDTO registerDTO) {
        log.info("用户注册请求：{}", registerDTO.getUsername());
        return authService.register(registerDTO);
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    @Operation(summary = "刷新Token", description = "使用旧Token获取新Token")
    public Result<?> refreshToken(@Parameter(description = "用户Token") @RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ", "");
        log.info("Token刷新请求");
        return authService.refreshToken(token);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户退出登录")
    public Result<?> logout(@Parameter(description = "用户Token") @RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ", "");
        log.info("用户登出请求");
        return authService.logout(token);
    }

    /**
     * 验证Token
     */
    @GetMapping("/validate")
    @Operation(summary = "验证Token", description = "验证用户Token是否有效")
    public Result<?> validateToken(@Parameter(description = "用户Token") @RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ", "");
        return authService.validateToken(token);
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    @Operation(summary = "健康检查", description = "检查服务是否正常运行")
    public Result<?> health() {
        return Result.success("认证服务运行正常");
    }

    /**
     * 测试密码加密（仅用于测试）
     */
    @GetMapping("/test-password")
    @Operation(summary = "测试密码加密", description = "测试密码加密功能")
    public Result<?> testPassword(@RequestParam String password) {
        String encoded = PasswordEncoder.encode(password);
        Map<String, Object> result = new HashMap<>();
        result.put("original", password);
        result.put("encoded", encoded);
        result.put("matches", PasswordEncoder.matches(password, encoded));
        
        // 测试数据库中admin的密码
        String dbPassword = "$2a$10$7JB720yubVSOfvam2PkPb.5/5.N0KxvLa0/QVlFyAYF2l8W1.H2KG";
        result.put("matchesDbAdmin", PasswordEncoder.matches(password, dbPassword));
        
        return Result.success("密码测试结果", result);
    }

    /**
     * 重置管理员密码（仅用于测试）
     */
    @PostMapping("/reset-admin-password")
    @Operation(summary = "重置管理员密码", description = "重置管理员密码为123456")
    public Result<?> resetAdminPassword() {
        return authService.resetAdminPassword();
    }
} 